<?php
/**
 * 游戏-掷骰子
 */
session_start();
$uid = @$_SESSION['id'] ? @$_SESSION['id'] : ''; //当前用户
if(!$uid){
	exit('请登录！');
}
//从game表中取值，查看游戏扣除积分
$xf = C_base::M('admin.gamegl')->game_s(array('id'=>3));
//从game_conf中取值
$tager = C_base::M('admin.gamegl')->gconf_ss(array('gameid'=>3),'jiangpin,jilv');

if($tager){
	$prize_arr =array();
	foreach ($tager as $k=>$v){
		$prize_arr[$k]['id'] = $k+1;
		$prize_arr[$k]['prize'] = $v['jiangpin'];
		$prize_arr[$k]['v'] = $v['jilv'];
	}
}
foreach ($prize_arr as $v) {
	$arr[$v['id']] = $v['v'];
}

$prize_id = getRand($arr); //根据概率获取奖项id
$res = $prize_arr[$prize_id - 1]; //中奖项
$data = array('award_id'=>$res['id'],'award_name'=>$res['prize']);
header("Content-type: application/json");
if(isset($_GET['callback'])){
	echo $_GET['callback']."(".json_encode($data).")";
}else{
	echo json_encode($data);
}

$record = array('uid'=>$uid,'gamename'=>$xf['name'],'jifen'=>$xf['jifen'],'time'=>time());
if($res['prize']){ //【写入中奖名单】
	$record['jiangpin'] = $data['award_name'];
	$record['zt'] = 1;
	//向game_winning表中写入数据
	C_base::M('admin.gamegl')->winn_c(array('uid'=>$uid,'gameid'=>2,'phone'=>'111','jiangpin'=>$data['award_name'],'time'=>time()));
}
//向game_record表中写入数据
C_base::M('admin.gamegl')->record_c($record);

function getRand($proArr) {
	$data = '';
	$proSum = array_sum($proArr); //概率数组的总概率精度
	 
	foreach ($proArr as $k => $v) { //概率数组循环
		$randNum = mt_rand(1, $proSum);
		if ($randNum <= $v) {
			$data = $k;
			break;
		} else {
			$proSum -= $v;
		}
	}
	unset($proArr);

	return $data;
}

/**
 * php数组
 * key
 * 恢复key
 */
function restore_array($arr){
	if (!is_array($arr)){ return $arr; }
	$c = 0; $new = array();
	while (list($key, $value) = each($arr)){
		if (is_array($value)){
			$new[$c] = restore_array($value);
		}
		else { $new[$c] = $value;}
		$c++;
	}
	return $new;
}
?>